// Ansible Playbook YAML 语言定义和智能提示
import * as monaco from 'monaco-editor'

// 全局变量来跟踪注册状态
let playbookLanguageRegistered = false
let playbookCompletionProvider = null

// 注册Ansible Playbook YAML语言
export const registerAnsiblePlaybookLanguage = () => {
  // 避免重复注册
  if (playbookLanguageRegistered) {
    console.log('Ansible Playbook语言已注册，跳过重复注册')
    return
  }

  try {
    // 注册语言
    monaco.languages.register({ id: 'ansible-yaml' })
    console.log('注册Ansible Playbook YAML语言成功')

    // 设置语言配置
    monaco.languages.setLanguageConfiguration('ansible-yaml', {
      wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
      comments: {
        lineComment: '#'
      },
      brackets: [
        ['{', '}'],
        ['[', ']'],
        ['(', ')']
      ],
      autoClosingPairs: [
        { open: '{', close: '}' },
        { open: '[', close: ']' },
        { open: '(', close: ')' },
        { open: '"', close: '"', notIn: ['string'] },
        { open: "'", close: "'", notIn: ['string', 'comment'] }
      ],
      surroundingPairs: [
        { open: '{', close: '}' },
        { open: '[', close: ']' },
        { open: '(', close: ')' },
        { open: '"', close: '"' },
        { open: "'", close: "'" }
      ],
      folding: {
        offSide: true
      }
    })

    // 设置语法高亮
    monaco.languages.setMonarchTokensProvider('ansible-yaml', {
      tokenizer: {
        root: [
          // 注释
          [/#.*$/, 'comment'],

          // YAML文档分隔符
          [/^---\s*$/, 'keyword.control'],
          [/^\.\.\.\s*$/, 'keyword.control'],

          // Ansible关键字（顶级）
          [/^(\s*)(name|hosts|tasks|vars|handlers|roles|become|gather_facts|serial|strategy)(\s*)(:)/,
           ['', 'keyword.ansible', '', 'delimiter']],

          // Task关键字
          [/^(\s*)(-\s*)(name|when|with_items|loop|register|ignore_errors|changed_when|failed_when|tags|become|become_user)(\s*)(:)/,
           ['', 'operator', 'key.ansible', '', 'delimiter']],

          // 模块名（任务中的模块）
          [/^(\s*)(-?\s*)(apt|yum|copy|file|template|service|systemd|shell|command|script|debug|set_fact|include|import_tasks)(\s*)(:)/,
           ['', 'operator', 'entity.name.function', '', 'delimiter']],

          // 变量引用 {{ variable }}
          [/\{\{\s*[\w\.\[\]\'\"]+\s*\}\}/, 'variable.ansible'],

          // Jinja2过滤器
          [/\|\s*\w+/, 'support.function'],

          // 字符串（双引号）
          [/"/, 'string', '@string_double'],

          // 字符串（单引号）
          [/'/, 'string', '@string_single'],

          // 布尔值
          [/\b(yes|no|true|false|on|off)\b/, 'constant.language'],

          // 数字
          [/\b\d+\b/, 'number'],

          // YAML键值对的键
          [/^(\s*)([a-zA-Z_][a-zA-Z0-9_]*)(\s*)(:)/, ['', 'key', '', 'delimiter']],

          // 列表项
          [/^(\s*)(-)/, ['', 'operator']],

          // 操作符
          [/[{}[\](),]/, 'delimiter'],
        ],

        string_double: [
          [/[^\\"]+/, 'string'],
          [/\\./, 'string.escape'],
          [/"/, 'string', '@pop']
        ],

        string_single: [
          [/[^\\']+/, 'string'],
          [/\\./, 'string.escape'],
          [/'/, 'string', '@pop']
        ]
      }
    })

    // 设置简化的自定义主题
    console.log('定义ansible-playbook-dark主题...')
    monaco.editor.defineTheme('ansible-playbook-dark', {
      base: 'vs-dark',
      inherit: true,
      rules: [
        // 基础语法高亮
        { token: 'comment', foreground: '6A9955', fontStyle: 'italic' },
        { token: 'string', foreground: 'CE9178' },
        { token: 'number', foreground: 'B5CEA8' },
        { token: 'keyword', foreground: '569CD6', fontStyle: 'bold' },
        { token: 'key', foreground: '9CDCFE' },
        { token: 'delimiter', foreground: 'D4D4D4' }
      ],
      colors: {
        'editor.background': '#1E1E1E',
        'editor.foreground': '#D4D4D4'
      }
    })
    console.log('ansible-playbook-dark主题定义完成')

    // 注册智能提示提供者
    playbookCompletionProvider = monaco.languages.registerCompletionItemProvider('ansible-yaml', {
      provideCompletionItems: (model, position) => {
        const word = model.getWordUntilPosition(position)
        const range = {
          startLineNumber: position.lineNumber,
          endLineNumber: position.lineNumber,
          startColumn: word.startColumn,
          endColumn: word.endColumn
        }

        const suggestions = []
        const lineText = model.getLineContent(position.lineNumber)
        const linePrefix = lineText.substring(0, position.column - 1)

        // 根据上下文提供不同的补全
        if (linePrefix.trim() === '' || linePrefix.trim() === '-') {
          // 顶级或任务级别的关键字
          const topLevelKeys = [
            { name: 'name', desc: '任务或play的名称' },
            { name: 'hosts', desc: '目标主机或主机组' },
            { name: 'tasks', desc: '任务列表' },
            { name: 'vars', desc: '变量定义' },
            { name: 'handlers', desc: '处理器定义' },
            { name: 'become', desc: '是否提权' },
            { name: 'gather_facts', desc: '是否收集facts' },
            { name: 'when', desc: '条件执行' },
            { name: 'with_items', desc: '循环项目' },
            { name: 'loop', desc: '循环' },
            { name: 'register', desc: '注册变量' },
            { name: 'tags', desc: '标签' }
          ]

          topLevelKeys.forEach(key => {
            suggestions.push({
              label: key.name,
              kind: monaco.languages.CompletionItemKind.Keyword,
              detail: key.desc,
              insertText: `${key.name}: `,
              documentation: key.desc,
              range: range
            })
          })
        }

        // 常用模块补全
        const commonModules = [
          { name: 'apt', desc: 'Debian/Ubuntu包管理' },
          { name: 'yum', desc: 'RedHat/CentOS包管理' },
          { name: 'copy', desc: '复制文件' },
          { name: 'file', desc: '文件操作' },
          { name: 'template', desc: '模板文件' },
          { name: 'service', desc: '服务管理' },
          { name: 'systemd', desc: 'Systemd服务管理' },
          { name: 'shell', desc: '执行shell命令' },
          { name: 'command', desc: '执行命令' },
          { name: 'debug', desc: '调试输出' },
          { name: 'set_fact', desc: '设置变量' },
          { name: 'include_tasks', desc: '包含任务文件' },
          { name: 'import_tasks', desc: '导入任务文件' }
        ]

        commonModules.forEach(module => {
          suggestions.push({
            label: module.name,
            kind: monaco.languages.CompletionItemKind.Function,
            detail: module.desc,
            insertText: `${module.name}:\n  `,
            documentation: module.desc,
            range: range
          })
        })

        return { suggestions }
      },
      triggerCharacters: [' ', ':', '-']
    })

    // 标记为已注册
    playbookLanguageRegistered = true
    console.log('Ansible Playbook YAML语言和智能提示注册成功')
  } catch (error) {
    console.error('注册Ansible Playbook YAML语言失败:', error)
  }
}

// 清理Ansible Playbook语言注册
export const unregisterAnsiblePlaybookLanguage = () => {
  if (playbookCompletionProvider) {
    try {
      playbookCompletionProvider.dispose()
      playbookCompletionProvider = null
      console.log('Ansible Playbook智能提示提供者已清理')
    } catch (error) {
      console.error('清理Ansible Playbook智能提示提供者失败:', error)
    }
  }

  // 重置注册状态
  playbookLanguageRegistered = false
}

// 获取默认的Playbook内容
export const getDefaultPlaybookContent = () => {
  return `---
- name: 示例Playbook
  hosts: all
  become: yes

  vars:
    app_name: "my-app"
    app_version: "1.0.0"

  tasks:
    - name: 更新系统包
      apt:
        update_cache: yes
        upgrade: dist
      when: ansible_os_family == "Debian"

    - name: 安装必要软件包
      package:
        name:
          - curl
          - wget
          - vim
        state: present

    - name: 创建应用目录
      file:
        path: "/opt/{{ app_name }}"
        state: directory
        mode: '0755'

    - name: 显示完成信息
      debug:
        msg: "Playbook执行完成！应用: {{ app_name }} 版本: {{ app_version }}"
`
}
